package com.sskj.gocoin.v.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.BaseKChartView;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.base.IValueFormatter;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.lzy.okgo.OkGo;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.m.bean.bean.Stock;
import com.sskj.gocoin.p.fragment.ChartPresenter;
import com.sskj.gocoin.utils.DataHelper;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.v.activity.MarketDetailActivity;
import com.sskj.gocoin.v.base.BaseFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;
import io.reactivex.disposables.Disposable;

/**
 * ProjectName：new_bfex
 * DESC: (类描述)
 * Created by 李岩 on 2018/7/5 0005
 * updateName:(修改人名称)
 * updateTime:(修改时间)
 * updateDesc:(修改内容)
 */
@Deprecated
public class ChartFragment extends BaseFragment<MarketDetailActivity, ChartPresenter> {
    @BindView(R2.id.minute_kchartview)
    KChartView mMinuteKchartview;  // K线
    private KChartAdapter mAdapter;

    private String goodsType;
    private String code;
    private boolean mIsMinute;
    private Disposable mDisposable;

    private boolean isLoading;
    private SimpleDateFormat minuteFormat = new SimpleDateFormat("mm");
    public String socketPrice;

    //    private List<Disposable> mDisposable = new ArrayList<>();

    /**
     * @param code 币种编码
     * @return
     */
    public static ChartFragment newInstance(String code, String goodsType, boolean isMinute) {
        ChartFragment chartFragment = new ChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString("code", code);
        bundle.putString("goodsType", goodsType);
        bundle.putBoolean("isMinute", isMinute);
        chartFragment.setArguments(bundle);
        return chartFragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_chart_view;
    }

    @Override
    public ChartPresenter getPresenter() {
        return new ChartPresenter();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        code = getArguments().getString("code");
        goodsType = getArguments().getString("goodsType");
        mIsMinute = getArguments().getBoolean("isMinute");
        //0 获取五大币数据
        mMinuteKchartview.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.activity_bg));
        mMinuteKchartview.showLoading();
        mPresenter.getStockInfo(goodsType, code, 1, 2, false);
        mMinuteKchartview.setDrawTabView(true);
        mMinuteKchartview.setMainUpColor(R.color.market_up);  // 设置k线颜色 涨
        mMinuteKchartview.setMainDownColor(R.color.market_down); // 设置k线颜色 跌
        mMinuteKchartview.setGridRows(2);
        mMinuteKchartview.setGridColumns(2);
        mMinuteKchartview.setVolumeMaGone(true);
        mMinuteKchartview.setValueFormatter(new IValueFormatter() {
            @Override
            public String format(float v) {
                return NumberUtil.keep2(v + "");
            }
        });
        if (mIsMinute) {
            mMinuteKchartview.setDrawMinuteStyle(true);
            //            mMinuteKchartview.setDrawGirdLine(false);
            mMinuteKchartview.setDateTimeFormatter(new TimeFormatter());
        } else {
            mMinuteKchartview.setDateTimeFormatter(new DateLFormatter());
        }
        mAdapter = new KChartAdapter();
        mMinuteKchartview.setAdapter(mAdapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mAdapter.getCount() <= 0) {
            mPresenter.getStockInfo(goodsType, code, 1, 2, false);
        }
    }

//    /**
//     * 开启定时刷新
//     */
//    private void time() {
//        mDisposable = Flowable.interval(20, TimeUnit.SECONDS)
//                .subscribe(a -> {
//                    if (mMinuteKchartview != null) {
//                        mMinuteKchartview.showLoading();
//                        mPresenter.getStockInfo(goodsType, code, 1, 2, true);
//                    }
//                });
//    }

    public void setChart(List<Stock> stockList, boolean update) {
        if (mMinuteKchartview != null) {
            mMinuteKchartview.hideLoading();
            Collections.reverse(stockList);
            DataHelper.calculate(stockList);
            mAdapter.datas.clear();
            if (!TextUtils.isEmpty(socketPrice)) {
                stockList.get(stockList.size() - 1).setClosingPrice(socketPrice);
            }
            mAdapter.addFooterData(stockList);
            isLoading = false;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        OkGo.getInstance().cancelAll();
    }

    public void upDate(Stock stock) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            Stock lastItem = (Stock) mAdapter.getItem(mAdapter.getCount() - 1);
            Long newTime = stock.getTimestamp();
            Long lastTime = lastItem.getTimestamp();
            long time = newTime - lastTime;
            boolean add = false;
            if (goodsType.equals("minute")) {
                add = time >= 1 * 60;
            } else if (goodsType.equals("minute5")) {
                add = time >= 5 * 60;
            } else if (goodsType.equals("minute15")) {
                add = time >= 15 * 60;
            } else if (goodsType.equals("minute30")) {
                add = time >= 30 * 60;
            } else if (goodsType.equals("day")) {
                add = time >= 24 * 60 * 60;
            }
            if (add) {
                mAdapter.getDatas().add(stock);
                mAdapter.notifyDataSetChanged();
            } else {
                if (stock.getHighPrice() > lastItem.getHighPrice()) {
                    lastItem.setHighestPrice(stock.getHighestPrice());
                }
                if (stock.getLowPrice() < lastItem.getLowPrice()) {
                    lastItem.setLowestPrice(stock.getLowestPrice());
                }
                lastItem.setOpeningPrice(stock.getOpeningPrice());
                mAdapter.getDatas().set(mAdapter.getCount() - 1, lastItem);
                mAdapter.notifyDataSetChanged();
            }
        }

    }


    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }


        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            try {
                return new Date(datas.get(position).getTimestamp() * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 向头部添加数据
         */
        public void addHeaderData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyDataSetChanged();
            }
        }


        /**
         * 向头部添加一条数据
         * <p>
         * public void addHeaderItemData(Stock obj) {
         * if (obj != null) {
         * datas.add(obj);
         * notifyDataSetChanged();
         * }
         * }
         * <p>
         * /**
         * 向尾部添加数据
         */
        public void addFooterData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         *
         * @param position 索引值
         */
        public void changeItem(int position, Stock data) {
            datas.set(position, data);
            notifyDataSetChanged();
        }

    }
}
